package com.security.door.core.dao.query;

import lombok.Data;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

@Data
public class Query {

    public enum Opt {
        /**
         * 操作类型
         */
        eq("="), gt(">"), lt("<"), gte(">="), lte("<="), nq("<>"), like("like"), lLike("lLike"), in("in"), notIn("not in"), isNull("is null"), isNotNull("is not null");
        private String value;

        Opt(String value) {
            this.value = value;
        }

        public static Opt parse(String value) {
            for (Opt opt : values()) {
                if (value.equals(opt.value)) {
                    return opt;
                }
            }
            return null;
        }

        @Override
        public String toString() {
            return this.value;
        }
    }

    private String key;
    private Opt opt = Opt.eq;
    private List value = new ArrayList();

    public Query() {
    }

    public Query(String key, Object value) {
        this.key = key;
        this.opt = Opt.eq;
        setValue(value);
    }

    public Query(String key, Opt opt, Object value) {
        this.key = key;
        this.opt = opt;
        setValue(value);
    }

    public String getKey() {
        return this.key;
    }

    public String getOpt() {
        return this.opt.toString();
    }

    public List getValue() {
        return this.value;
    }

    public void setKey(String key) {
        this.key = key;
    }

    public void setOpt(String opt) {
        this.opt = Opt.parse(opt);
    }

    public void setValue(Object value) {
        if (value == null) {
            return;
        }
        if (value instanceof Collection) {
            Collection list = (Collection) value;
            if (CollectionUtils.isEmpty(list)) {
                return;
            }
            this.value.addAll(list);
        } else {
            this.value.add(value);
        }
    }
}